if __name__ == '__main__':
    pass

import urllib2,sys,datetime
from BeautifulSoup import BeautifulSoup,NavigableString

def printText(tags):
    for tag in tags:
        if tag.__class__ == NavigableString:
            print tag,
        else:
            printText(tag)

prgs = [ ]

urls = [ "http://www.rtve.es/television/components/parrilla/mod_parrilla_tveint_hoy.inc",
         "http://www.rtve.es/television/components/parrilla/mod_parrilla_tveint_manana.inc",
         "http://www.rtve.es/television/components/parrilla/mod_parrilla_tveint_pasado.inc" ]

for url in urls:
    html = urllib2.urlopen(url).read()
    soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES)
    chx = soup.find("div", { "id" : "programacion" }).findAll("ul", { "rel" : "tve" })
    
    tzone = " +0100"
    chnid = "tvei.rtve.es"
    
    ch = chx[0]
    prx = ch.findAll("li")
    for pr in prx:
        time = pr.find("span");
        if time != None:
            prg = { "time": time.getText().replace(":", "") }
            lk = pr.find("a", { "rel" : "facebox" } )
            prg["title"] = lk.get("title")
            prgs.append(prg)

print "<?xml version=\"1.0\"?>"
print "<tv>"
print "<channel id=\"" + chnid + "\">"
print " <display-name>TVE International Europa</display-name>"
print "</channel>"
    
day = datetime.datetime.today()
prday = day.strftime("%Y%m%d")
one_day = datetime.timedelta(days=1)

for i in range(len(prgs) - 1):
    print "<programme start=\"" + prday + prgs[i]["time"] + tzone + "\"" 
    if  prgs[i]["time"] > prgs[i + 1]["time"]:
        day = day + one_day
        prday = day.strftime("%Y%m%d")
    print "stop=\"" + prday + prgs[i + 1]["time"] + tzone + "\" channel=\"" + chnid + "\">"
    print "<title lang=\"es\">" + prgs[i]["title"].encode("utf-8") + "</title>"
    print "</programme>" 

print "</tv>"

'''
print len(channels)

printText(soup.findAll("p"))

print soup.prettify()

print "".join(soup.findAll("p", text=re.compile(".")))
'''
